package com.tangx.wemedia.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.tangx.file.service.FileStorageService;
import com.tangx.model.common.dtos.PageResponseResult;
import com.tangx.model.common.dtos.ResponseResult;
import com.tangx.model.common.enums.AppHttpCodeEnum;
import com.tangx.model.wemedia.dtos.WmMaterialDto;
import com.tangx.model.wemedia.pojos.WmMaterial;
import com.tangx.utils.common.ThreadLocalUtil;
import com.tangx.wemedia.mapper.WmMaterialMapper;
import com.tangx.wemedia.service.WmMaterialService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.Date;
import java.util.UUID;

/**
 * <p>
 * 自媒体图文素材信息表 服务实现类
 * </p>
 *
 * @author tangx
 */
@Slf4j
@Service
public class WmMaterialServiceImpl extends ServiceImpl<WmMaterialMapper, WmMaterial> implements WmMaterialService {

    @Autowired
    private FileStorageService fileStorageService;

    @Override
    public ResponseResult uploadPicture(MultipartFile multipartFile) {
        //1.判断参数合法性
        if(multipartFile==null || multipartFile.isEmpty() || multipartFile.getSize()==0){
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID, "文件参数非法");
        }

        //2.判断用户是否登录
        Integer userId = ThreadLocalUtil.getUserId();
        if(userId==null){
            return ResponseResult.errorResult(AppHttpCodeEnum.NEED_LOGIN);
        }

        //3.为文件生成唯一名称  a.b.c.png
        String filePrefixName = UUID.randomUUID().toString().replace("-",""); //文件前缀名
        //原始文件名
        String originalFileName = multipartFile.getOriginalFilename();
        int lastIndex = originalFileName.lastIndexOf("."); //获取最后一个.的索引位置
        String filePostFixName = originalFileName.substring(lastIndex); //文件后缀名（扩展名）
        String fileFullName = filePrefixName + filePostFixName;//完整文件名

        //4.将文件上传到MinIO
        try {
            String url = fileStorageService.uploadImgFile("", fileFullName, multipartFile.getInputStream());

            //5.构建素材实例并保存
            WmMaterial wmMaterial = new WmMaterial();
            wmMaterial.setUserId(userId);//登录用户ID
            wmMaterial.setUrl(url); //访问路径
            wmMaterial.setIsCollection(0);//未收藏
            wmMaterial.setType(0);//图片类型
            wmMaterial.setCreatedTime(new Date());
            this.save(wmMaterial);

            //6.响应数据
            return ResponseResult.okResult(wmMaterial);
        } catch (IOException e) {
            e.printStackTrace();
            return ResponseResult.errorResult(AppHttpCodeEnum.SERVER_ERROR, "文件上传失败");
        }
    }


    @Override
    public ResponseResult list(WmMaterialDto dto) {
        //1.设置分页参数默认值
        dto.checkParam();

        //2.判断用户是否登录
        Integer userId = ThreadLocalUtil.getUserId();
        if (userId == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.NEED_LOGIN);
        }

        //3.拼接查询条件
        LambdaQueryWrapper<WmMaterial> lambdaQueryWrapper = new LambdaQueryWrapper();
        lambdaQueryWrapper.eq(WmMaterial::getUserId, userId);//固定查询条件：用户ID
        if(dto.getIsCollection()!=null){
            lambdaQueryWrapper.eq(WmMaterial::getIsCollection, dto.getIsCollection());//动态查询条件：收藏字段
        }
        lambdaQueryWrapper.orderByDesc(WmMaterial::getCreatedTime);//查询结果根据创建时间倒排序

        //4.执行分页查询
        IPage<WmMaterial> page = new Page<>(dto.getPage(),dto.getSize());

        this.page(page, lambdaQueryWrapper);

        //5.封装分页响应结果实例
        ResponseResult responseResult = new PageResponseResult(dto.getPage(), dto.getSize(), page.getTotal());
        responseResult.setData(page.getRecords());//当前页列表数据

        //6.响应数据
        return responseResult;
    }
}
